<template>
  <div class="form-wrapper">
    <header class="form-header">
      <BaseButton @click="handleCancel">
        <ChevronsLeft class="icon-base" />
      </BaseButton>
      <h1 class="page-title">{{ isEdit ? '编辑地址' : '新增地址' }}</h1>
      <div style="width: 24px"></div>
    </header>

    <form @submit.prevent="handleSubmit" class="form-container">
      <div class="form-group">
        <label class="form-label">出发地址</label>
        <input
          type="text"
          v-model="formData.from"
          class="form-input"
          placeholder="例：珠海校区榕园11号"
          required
        />
      </div>

      <div class="form-group">
        <label class="form-label">到达地址</label>
        <input
          type="text"
          v-model="formData.to"
          class="form-input"
          placeholder="例：北京市朝阳区..."
          required
        />
      </div>

      <div class="form-group">
        <label class="form-label">联系电话</label>
        <input
          type="tel"
          v-model="formData.phone"
          class="form-input"
          placeholder="请输入11位手机号"
          pattern="[0-9]{11}"
          required
        />
      </div>

      <div class="checkbox-wrapper">
        <label class="checkbox-label">
          <input
            type="checkbox"
            v-model="formData.isPrimary"
            class="checkbox-input"
          />
          <span class="checkbox-text">设为主地址</span>
        </label>
      </div>

      <button type="submit" class="submit-button">
        保存
      </button>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ChevronsLeft } from 'lucide-vue-next'
import axios from 'axios'
import BaseButton from '@/components/BaseButton.vue'

const router = useRouter()
const route = useRoute()

const isEdit = ref(false)
const addressId = ref(null)

const formData = ref({
  from: '',
  to: '',
  phone: '',
  isPrimary: false
})

// 从路由参数初始化表单
onMounted(() => {
  const { mode, id, from, to, phone, isPrimary } = route.query
  
  console.log('mode:', mode, 'id:', id, 'from:', from, 'to:', to, 'phone:', phone, 'isPrimary:', isPrimary)
  if (mode === 'edit' && id) {
    isEdit.value = true
    addressId.value = id
    formData.value = {
      from: from || '',
      to: to || '',
      phone: phone || '',
      isPrimary: isPrimary === '1'
    }
  }
})

const handleSubmit = async () => {
  try {
    const currentUser = JSON.parse(localStorage.getItem('user'));
    const userId = currentUser ? currentUser.uid : null;

    if (!userId) {
      alert('未找到用户信息，请重新登录');
      return;
    }

    let response;
    
    if (isEdit.value && addressId.value) {
      // 修改地址 - 确保 address_id 是数字类型
      response = await axios.put('/api/auth/addresses', 
        {
          uid: userId,
          pickup_address: formData.value.from,
          delivery_address: formData.value.to,
          phone_number: formData.value.phone,
          is_primary: formData.value.isPrimary,
          address_id: parseInt(addressId.value) // 转换为数字
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': localStorage.getItem('token')
          }
        }
      );
    } else {
      // 新增地址 - 保持原有逻辑
      response = await axios.post('/api/auth/addresses', 
        {
          uid: userId,
          pickup_address: formData.value.from,
          delivery_address: formData.value.to,
          phone_number: formData.value.phone,
          is_primary: formData.value.isPrimary
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': localStorage.getItem('token')
          }
        }
      );
    }

    if (response.data.code === 0) {
      alert(isEdit.value ? '修改地址成功' : '新增地址成功');
      router.go(-1);
    } else {
      throw new Error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存地址失败:', error);
    alert(error.response?.data?.message || error.message || '保存失败');
  }
}

const handleCancel = () => {
  router.go(-1)
}
</script>

<style scoped>
.form-wrapper {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 16px;
}

.form-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.btn-back {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  cursor: pointer;
}

.page-title {
  /* 原先 font-size: 18px; */
  font-size: var(--font-size-large);
  font-weight: 600;
  color: #1a1a1a;
}

.form-container {
  max-width: 600px;
  margin: 0 auto;
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  /* 原先 font-size: 15px; */
  font-size: var(--font-size-normal);
  font-weight: 500;
  color: #333333;
  margin-bottom: 8px;
}

.form-input {
  /* 原先 font-size: 15px; */
  font-size: var(--font-size-normal);
  width: 100%;
  height: 48px;
  padding: 0 16px;
  color: #333333;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: #ffffff;
  transition: all 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-input::placeholder {
  color: #9ca3af;
}

.checkbox-wrapper {
  margin-bottom: 24px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox-input {
  width: 18px;
  height: 18px;
  margin-right: 8px;
  cursor: pointer;
}

.checkbox-text {
  /* 原先 font-size: 15px; */
  font-size: var(--font-size-normal);
  color: #333333;
}

.submit-button {
  width: 100%;
  padding: 15px;
  background-color: var(--primary-color);
  color: var(--text-light);
  border: none;
  border-radius: var(--border-radius-small);
  margin-top: 20px;
  cursor: pointer;
}



.icon-base {
  width: 24px;
  height: 24px;
  color: #1a1a1a;
}

@media (max-width: 640px) {
  .form-container {
    padding: 20px;
  }
  
  .form-input {
    height: 44px;
  }
  
  .submit-button {
    height: 44px;
  }
}
</style>
